//
//  HomeCollectionViewController.swift
//  Photos
//
//  Created by zhangjianyun on 17/7/28.
//  Copyright © 2017年 com.taihejiacheng. All rights reserved.
//

import UIKit

let reuseIdentifier_Shot = "ShotCollectionViewCell"

class HomeCollectionViewController: UICollectionViewController {
    
    fileprivate var shots:[Shot] = [Shot]() {
        didSet{
            self.collectionView?.reloadData()
        }
    }
    
    fileprivate var cellWidth:CGFloat = 0.0
    fileprivate var cellHeight:CGFloat = 0.0
    
    fileprivate let cellVerticalMargin:CGFloat = 20.0
    fileprivate let cellHorizontalMargin:CGFloat = 20.0
    
    var API_URL = Config.URL
    
    
    var shotPages = 1
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func loadShots(){
        self.collectionView!.backgroundColor = UIColor.hexStr("f5f5f5", alpha: 1.0)
        
        cellWidth = self.view.bounds.width
        cellHeight = self.view.bounds.height / 2.5
        
        self.collectionView?.register(UINib(nibName: "ShotCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: reuseIdentifier_Shot)
        
        DribbleObjectHandler.getShots(API_URL, callback: {(shots) -> Void in
            self.shots = shots
        })
        
        let refreshControl = UIRefreshControl()
        refreshControl.addTarget(self, action: #selector(HomeCollectionViewController.refreshInvoked(_:)), for: UIControlEvents.valueChanged)
        collectionView?.addSubview(refreshControl)
    }

    func refreshInvoked(_ sender:AnyObject) {
        sender.beginRefreshing()
        collectionView?.reloadData()
        sender.endRefreshing()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return shots.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier_Shot, for: indexPath) as! ShotCollectionViewCell
        
        let shot = shots[indexPath.row]
        
        cell.imageView.sd_setImage(with: URL(string: shot.image_url)!)
        
        cell.designerIcon.layer.cornerRadius = cell.designerIcon.bounds.width / 2
        cell.designerIcon.layer.masksToBounds = true
        
        cell.shotName.text = "Banner"
        cell.designerName.text = "Banner"
        cell.viewLabel.text = shot.recommend_theme

        
        if shots.count - 1 == indexPath.row && shotPages < 20 {
            shotPages += 1
            print(shotPages)
            let url = API_URL + String(shotPages)
            DribbleObjectHandler.getShots(url, callback: {(shots) -> Void in
                //                self.shots = shots
                
                for shot in shots {
                    self.shots.append(shot)
                }
            })
        }

    
        return cell
    }

    
    // MARK: UICollectionViewDelegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
        return CGSize(width: cellWidth - cellHorizontalMargin, height: cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
        return cellVerticalMargin
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
        return 0.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let _ = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier_Shot, for: indexPath) as! ShotCollectionViewCell
        let vc = ImageModalViewController(nibName: "ImageModalViewController", bundle: nil)
        
        vc.modalPresentationStyle = .fullScreen
        vc.modalTransitionStyle = .crossDissolve
        
        let cell = collectionView
        
        
        vc.imageView.image =
//        let downloadQueue = DispatchQueue(label: "com.naoyashiga.processdownload", attributes: [])
//        
//        downloadQueue.async{
//            let data = try? Data(contentsOf: URL(string: shot.image_url)!)
//            
//            var image: UIImage?
//            
//            if data != nil {
//                image = UIImage(data: data!)!
//            }
//            
//            DispatchQueue.main.async{
//                vc.imageView.image = image
//            }
//        }
        self.navigationController?.pushViewController(vc, animated: true)
        //parent?.present(vc, animated: true, completion: nil)
    }

}
